package com.fengke.csc.action.agentProfile;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;

import com.fengke.csc.action.BaseAction;
import com.fengke.dao.model.AdminModel;
import com.fengke.service.AgentProfileService;
import com.fengke.service.CacheService;
import com.fengke.service.vo.AgentProfileVO;
import com.fengke.service.vo.RoleVO;
import com.fengke.util.Constants;
import com.fengke.util.LoggerFactory;
import com.fengke.util.StringUtil;

public class AgentProfileAction extends BaseAction {
	private static final long serialVersionUID = 9124577204629126559L;
	private Logger logger = LoggerFactory.getLogger(AgentProfileAction.class);
	private AgentProfileService agentProfileService;
	private CacheService cacheService;
	private List<AgentProfileVO> agentProfileVOList = new ArrayList<AgentProfileVO>();
	private AgentProfileVO agentProfileVO = new AgentProfileVO();
	private List<RoleVO> roleVOList = new ArrayList<RoleVO>();
	public String agentProfileManager() {
		logger.debug("agentProfileManager");
		if(getPageBean().getCurrentPage() == null || getPageBean().getCurrentPage() <= 0) {
			getPageBean().setCurrentPage(1);
		}
		
		getPageBean().setPageSize(Constants.PageSize.CSC_PAGE_SIZE);
		
		AgentProfileVO sessionAgentProfileVO = (AgentProfileVO) this.getSession(false).getAttribute(Constants.SessionProfileName.CSC_PROFILE_NAME);
		if(sessionAgentProfileVO == null || sessionAgentProfileVO.getAdminModel() == null) {
			return Constants.ActionReturnName.NO_LOGIN;
		}
		
		// 获取总量
		Integer agentProfileVOListSize = null;
		
		if(!sessionAgentProfileVO.isSuperAdmin() && !sessionAgentProfileVO.isAdmin()) {
			agentProfileVOListSize = 1;
			getPageBean().setResultItemCount(agentProfileVOListSize);
			if (agentProfileVOList == null) {
				agentProfileVOList = new ArrayList<AgentProfileVO>();
			}
			agentProfileVOList.add(sessionAgentProfileVO);
		} else {
			try {
				agentProfileVOListSize = agentProfileService.researchAgentProfileVOListSize(agentProfileVO);
			} catch (Exception e) {
				logger.error("agentProfileManager researchAgentProfileVOListSize Exception! agentProfileVO=" + agentProfileVO, e);
				this.addPageDangerMessage("获取结果集数量异常！");
			}
			
			if(agentProfileVOListSize != null && agentProfileVOListSize > 0) {
				getPageBean().setResultItemCount(agentProfileVOListSize);
				try {
					agentProfileVOList = agentProfileService.researchAgentProfileVOList(agentProfileVO, (getPageBean().getCurrentPage() - 1) * getPageBean().getPageSize(), getPageBean().getPageSize());
				} catch (Exception e) {
					logger.error("agentProfileManager researchAgentProfileVOListSize Exception! agentProfileVO=" + agentProfileVO, e);
					this.addPageDangerMessage("获取结果集异常！");
				}
			} else {
				getPageBean().setResultItemCount(0);
			}
		}
		
		return Constants.ActionReturnName.SUCCESS;
	}
	public String preCreateAgentProfile() {
		logger.debug("preCreateAgentProfile...");
		this.setRequestAttr("actionType", "create");
		// 处理权限相关
		initMyAccessRoleVOList();
		return Constants.ActionReturnName.SUCCESS;
	}
	public String createAgentProfile() {
		this.setRequestAttr("actionType", "create");
		preCreate();
		if(this.hasPageDangerMessage()) {
			initMyAccessRoleVOList();
			return INPUT;
		}
		
		AgentProfileVO sessionAgentProfileVO = (AgentProfileVO) this.getSession(false).getAttribute(Constants.SessionProfileName.CSC_PROFILE_NAME);
		if(sessionAgentProfileVO == null || sessionAgentProfileVO.getAdminModel() == null) {
			return Constants.ActionReturnName.NO_LOGIN;
		}
		
		Long profileId = null;
		try {
			profileId = agentProfileService.createAgentProfile(agentProfileVO);
		} catch (Exception e) {
			logger.error("createAgentProfile Exception! agentProfileVO=" + agentProfileVO, e);
		}
		
		if(profileId != null) {
			// 插入成功
			this.addPageSuccessMessage("新建数据成功！");
			agentProfileVO.getAdminModel().setId(profileId);
		} else {
			// 插入失败
			this.addPageDangerMessage("插入失败！");
			return INPUT;
		}
		
		try {
			cacheService.invalidAdminCache();
		} catch (Exception e) {
			logger.error("createAgentProfile invalidAdminCache Exception!", e);
		}
		
		return Constants.ActionReturnName.SUCCESS;
	}
	private void initMyAccessRoleVOList() {
		AgentProfileVO sessionAgentProfileVO = (AgentProfileVO) this.getSession(false).getAttribute(Constants.SessionProfileName.CSC_PROFILE_NAME);
		if(sessionAgentProfileVO.isSuperAdmin() || sessionAgentProfileVO.isAdmin()) {
			initRoleVOList();
		}
		if(sessionAgentProfileVO.isMerchant()) {
			RoleVO vo = new RoleVO();
			vo.setRoleModel(sessionAgentProfileVO.getAdminRoleModelList().get(0).getRoleModel());
			roleVOList.add(vo);
		}
	}
	private void initRoleVOList() {
		try {
			roleVOList = agentProfileService.researchRoleVOList(new RoleVO());
		} catch (Exception e) {
			logger.error("initRoleVOList researchRoleVOList Exception!", e);
			this.addPageDangerMessage("获取权限列表异常！");
		}
	}
	private void preCreate() {
		// 参数校验
		if(agentProfileVO == null || agentProfileVO.getAdminModel() == null) {
			this.addPageDangerMessage("关键参数不能为空！");
			return ;
		}
		// username唯一性校验
		// 非空字段校验等等
		if(StringUtil.isEmpty(agentProfileVO.getAgentRoles())) {
			this.addPageDangerMessage("权限不能为空！");
		}
	}
	public String preUpdateAgentProfile() {
		this.setRequestAttr("actionType", "update");
		if(agentProfileVO == null || agentProfileVO.getAdminModel() == null || agentProfileVO.getAdminModel().getId() == null) {
			return Constants.ActionReturnName.ERROR;
		}
		Long agentProfileId = agentProfileVO.getAdminModel().getId();
		agentProfileVO = new AgentProfileVO();
		agentProfileVO.setAdminModel(new AdminModel());
		agentProfileVO.getAdminModel().setId(agentProfileId);
		try {
			agentProfileVO = agentProfileService.researchAgentProfileById(agentProfileVO);
		} catch (Exception e) {
			logger.error("preUpdateAgentProfile researchAgentProfileById Exception! agentProfileId=" + agentProfileId, e);
			this.addPageDangerMessage("检索商家信息出现异常！");
		}
		
		initMyAccessRoleVOList();
		
		return Constants.ActionReturnName.SUCCESS;
	}
	public String updateAgentProfile() {
		this.setRequestAttr("actionType", "update");
		preUpdate();
		if(this.hasPageDangerMessage()) {
			return Constants.ActionReturnName.SUCCESS;
		}
		// 更新数据
		int count = 0;
		try {
			count = agentProfileService.updateAgentProfileById(agentProfileVO);
		} catch (Exception e) {
			logger.error("updateAgentProfile updateAgentProfileById Exception! agentProfileVO=" + agentProfileVO, e);
		}
		
		if(count <= 0) {
			this.addPageDangerMessage("未能更新任何数据！");
		} else {
			this.addPageSuccessMessage("数据更新成功！");
		}
		
		try {
			cacheService.invalidAdminCache();
		} catch (Exception e) {
			logger.error("updateAgentProfile invalidAdminCache Exception!", e);
		}
		
		return Constants.ActionReturnName.SUCCESS;
	}
	private void preUpdate() {
		if(agentProfileVO == null || agentProfileVO.getAdminModel() == null || agentProfileVO.getAdminModel().getId() == null) {
			this.addPageDangerMessage("关键参数为空！");
			return;
		}
	}
	public String deleteAgentProfile() {
		logger.debug("deleteAgentProfile");
		String deletedAgentProfileIds = ((String[]) (this.getValue().get("deletedAgentProfileIds")))[0];
		if(deletedAgentProfileIds == null || StringUtil.isEmpty(deletedAgentProfileIds)) {
			this.addPageWarningMessage("待删除条目为空！");
			return Constants.ActionReturnName.SUCCESS;
		}
		String[] ids = deletedAgentProfileIds.split(" ");
		try {
			agentProfileService.deleteAgentProfileByIds(Arrays.asList(ids));
		} catch (Exception e) {
			logger.error("删除商家失败！ids=" + ids, e);
			this.addPageDangerMessage("删除商家失败！");
			return Constants.ActionReturnName.SUCCESS;
		}
		this.addPageSuccessMessage("删除成功！");
		try {
			cacheService.invalidAdminCache();
		} catch (Exception e) {
			logger.error("deleteAgentProfile invalidAdminCache Exception！", e);
		}
		
		return Constants.ActionReturnName.SUCCESS;
	}
	public String agentProfileValidator() {
		String property = this.getRequest().getParameter("property");
		String propertyValue = this.getRequest().getParameter("propertyValue");
		String agentProfileId = this.getRequest().getParameter("agentProfileId");
		if(StringUtil.isEmpty(property) || StringUtil.isEmpty(propertyValue)) {
			responseJsonString("false");
			return null;
		}
		boolean validResult = false;
		if("username".equals(property)) {
			// 用户名非空校验
			validResult = validUsername(propertyValue, agentProfileId);
		}
		responseJsonString(String.valueOf(validResult));
		return null;
	}
	public String agentProfileDetail() {
		if(agentProfileVO == null || agentProfileVO.getAdminModel() == null || agentProfileVO.getAdminModel().getId() == null) {
			this.addPageDangerMessage("关键参数不能为空！");
			return "input";
		}
		Long agentProfileId = agentProfileVO.getAdminModel().getId();
		try {
			agentProfileVO = agentProfileService.researchAgentProfileById(agentProfileVO);
		} catch (Exception e) {
			logger.error("agentProfileDetail researchAgentProfileById Exception! agentProfileId=" + agentProfileId, e);
			this.addPageDangerMessage("检索商户信息异常！");
			return "input";
		}
		return Constants.ActionReturnName.SUCCESS;
	}
	private boolean validUsername(String value, String agentProfileId) {
		if(agentProfileVO == null) {
			agentProfileVO = new AgentProfileVO();
		}
		if(agentProfileVO.getAdminModel() == null) {
			agentProfileVO.setAdminModel(new AdminModel());
		}
		agentProfileVO.getAdminModel().setUsername(value);
		if(!StringUtil.isEmpty(agentProfileId)) {
			agentProfileVO.getAdminModel().setId(Long.parseLong(agentProfileId));
		}
		try {
			return agentProfileService.checkAdminUsernameUnique(agentProfileVO);
		} catch (Exception e) {
			this.logger.error("validUsername checkAdminUsernameUnique Exception! agentProfileVO=" + agentProfileVO, e);
		}
		return false;
	}
	private void responseJsonString(String result) {
		this.getResponse().setContentType("application/json");
		this.getResponse().setCharacterEncoding("UTF-8");
		PrintWriter writer = null;
		try {
			writer = this.getResponse().getWriter();
			writer.write(result);
			writer.flush();
		} catch (IOException e) {
			this.logger.error("reposonJsonString Exception ! result=" + result, e);
		} finally {
			if(writer != null) {
				writer.close();
			}
		}
	}
	public AgentProfileService getAgentProfileService() {
		return agentProfileService;
	}
	public void setAgentProfileService(AgentProfileService agentProfileService) {
		this.agentProfileService = agentProfileService;
	}
	public CacheService getCacheService() {
		return cacheService;
	}
	public void setCacheService(CacheService cacheService) {
		this.cacheService = cacheService;
	}
	public List<AgentProfileVO> getAgentProfileVOList() {
		return agentProfileVOList;
	}
	public void setAgentProfileVOList(List<AgentProfileVO> agentProfileVOList) {
		this.agentProfileVOList = agentProfileVOList;
	}
	public AgentProfileVO getAgentProfileVO() {
		return agentProfileVO;
	}
	public void setAgentProfileVO(AgentProfileVO agentProfileVO) {
		this.agentProfileVO = agentProfileVO;
	}
	public List<RoleVO> getRoleVOList() {
		return roleVOList;
	}
	public void setRoleVOList(List<RoleVO> roleVOList) {
		this.roleVOList = roleVOList;
	}
}
